﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace WikiMiner
{
    public class Links : JSPTask
    {
        public class LinksResult : Article
        {
        }

        private class _Store
        {
            public int a;
            public string b;
            public int i;

            internal LinksResult ToLinksResult()
            {
                return new LinksResult() { title = b, id = i };
            }
        }

        private static List<_Store> cache = new List<_Store>();

        static Links()
        {
            try
            {
                StreamReader sr = new StreamReader("links.cache", Encoding.Unicode);

                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] split = line.Split(new char[] { '\t' });
                    cache.Add(new _Store() { a = int.Parse(split[0]), b = split[1], i = int.Parse(split[2]) });
                }

                sr.Close();
            }
            catch
            {
            }
        }

        public static void Save()
        {
            StreamWriter sw = new StreamWriter(File.Create("links.cache"), Encoding.Unicode);

            // lock (cache)
            {
                foreach (var entry in cache)
                    sw.WriteLine(entry.a + "\t" + entry.b + '\t' + entry.i);
            }
            sw.Close();
        }

        public static LinksResult[] GetOutLinks(int id)
        {
            return Get(id, false, true, -1);
        }

        public static LinksResult[] GetInLinks(int id)
        {
            return Get(id, true, false, -1);
        }
        public static LinksResult[] GetOutLinks(int id, int id2)
        {
            return Get(id, false, true, id2);
        }

        public static LinksResult[] GetInLinks(int id, int id2)
        {
            return Get(id, true, false, id2);
        }
        
        public static LinksResult[] Get(int id, bool ins, bool outs, int id2)
        {
            List<LinksResult> results = new List<LinksResult>();

            Article dest = Search.Get(id2);
            // lock (cache)
            {
                foreach (var entry in cache)
                    if ((entry.a == id))
                    {
                        results.Add(entry.ToLinksResult());
                    }
            }

            if (results.Count == 0)
            {
                try
                {
                    XmlDocument doc = 
                        (id2!=-1 && astaravailable) ? 
                        GetXml(string.Format(astarurl, id, id2)) :
                        GetXml(string.Format(linkurl, id));

                    string articlename = doc.SelectSingleNode("WikipediaMinerResponse/SearchResponse/Article").Attributes["title"].Value;


                    foreach (XmlNode node in doc.SelectNodes("WikipediaMinerResponse/SearchResponse/Article/SharedLinkList/SharedLink"))
                    {
                        {
                            _Store entry = new _Store()
                            {
                                a = id,
                                b = node.Attributes["title"].Value,
                                i = int.Parse(node.Attributes["id"].Value)
                            };

                            cache.Add(entry);

                            if (outs)
                                results.Add(entry.ToLinksResult());
                        }

                        {
                            _Store entry = new _Store()
                            {
                                a = int.Parse(node.Attributes["id"].Value),
                                b = articlename,
                                i = id
                            };

                            cache.Add(entry);

                            if (outs)
                                results.Add(entry.ToLinksResult());
                        }
                        if ((id2!=-1 && astaravailable) && dest != null )
                            Relatedness.Add(dest.title, 
                                node.Attributes["title"].Value,
                                float.Parse(node.Attributes["relatednessdest"].Value));

                        Relatedness.Add(articlename, node.Attributes["title"].Value, float.Parse(node.Attributes["relatedness"].Value));
                    }

                    foreach (XmlNode node in doc.SelectNodes("WikipediaMinerResponse/SearchResponse/Article/LinkOutList/LinkOut"))
                    {
                        _Store entry = new _Store()
                        {
                            a = id,
                            b = node.Attributes["title"].Value,
                            i = int.Parse(node.Attributes["id"].Value)
                        };

                        cache.Add(entry);

                        if (outs)
                            results.Add(entry.ToLinksResult());

                        if ((id2 != -1 && astaravailable) && dest != null)
                            Relatedness.Add(dest.title,
                                node.Attributes["title"].Value,
                                float.Parse(node.Attributes["relatednessdest"].Value));

                        Relatedness.Add(articlename, entry.b, float.Parse(node.Attributes["relatedness"].Value));
                    }

                    foreach (XmlNode node in doc.SelectNodes("WikipediaMinerResponse/SearchResponse/Article/LinkInList/LinkIn"))
                    {
                        _Store entry = new _Store()
                        {
                            a = int.Parse(node.Attributes["id"].Value),
                            b = articlename,
                            i = id
                        };
                        
                        cache.Add(entry);

                        if (ins)
                            results.Add(entry.ToLinksResult());

                        if ((id2 != -1 && astaravailable) && dest != null)
                            Relatedness.Add(dest.title,
                                node.Attributes["title"].Value,
                                float.Parse(node.Attributes["relatednessdest"].Value));

                        Relatedness.Add(articlename, entry.b, float.Parse(node.Attributes["relatedness"].Value));
                    }

                    Save();
                }
                catch
                {
                    return new LinksResult[0];
                }
            }

            return results.ToArray();
        }     
    }
}
